<template>
	<view>
		<view class="section">
			<button @click="downloadNetworkImage" class="custom-btn download-btn">下载网络图片</button>
			<!-- 下载进度提示（居中显示，补充进度条样式） -->
			<view v-if="downloadProgress > 0 && downloadProgress < 100" class="progress-container">
				<text class="progress-text">下载进度：{{ downloadProgress }}%</text>
				<!-- 进度条背景 -->
				<view class="progress-bg">
					<!-- 进度条填充（随进度变化） -->
					<view class="progress-fill" :style="{ width: downloadProgress + '%' }"></view>
				</view>
			</view>
			<!-- 图片居中显示 -->
			<image v-if="networkImageUrl" :src="networkImageUrl" mode="widthFix" class="preview-image"></image>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				networkImageUrl: '',
				downloadProgress: 0				
			}
		},
		methods: {
			downloadNetworkImage() {
				// 重置状态：清空旧图片、重置进度
				this.networkImageUrl = '';
				this.downloadProgress = 0;
				
				const downloadTask = uni.downloadFile({
					url: 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg', // 不修改原地址
					success: (res) => {
						if (res.statusCode === 200) {
							this.downloadProgress = 100; // 下载完成瞬间显示100%
							this.networkImageUrl = res.tempFilePath;
							uni.showToast({
								title: '图片下载完成',
								icon: 'success'
							});
							// 3秒后隐藏进度（保持原逻辑）
							setTimeout(() => {
								this.downloadProgress = 0;
							}, 3000);
						}
					},
					fail: (err) => {
						console.error('下载图片失败', err);
						this.downloadProgress = 0;
						uni.showToast({
							title: '图片下载失败',
							icon: 'none'
						});
					}
				});
				
				// 强化进度监听：确保实时更新（核心补充，不修改原有逻辑）
				downloadTask.onProgressUpdate((res) => {
					// 强制实时更新进度值，避免响应延迟
					this.$nextTick(() => {
						this.downloadProgress = res.progress;
					});
					console.log(`下载进度：${res.progress}%`);
				});
			}			
		}
	}
</script>

<style>
	/* 保持原有所有样式不变 */
	.download-btn {
		background-color: #3CD6FF;
	}

	.section {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center; /* 图片和进度提示居中 */
		gap: 20rpx;
	}

	.weather-card {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.weather-item {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
	}

	.weather-item:last-child {
		margin-bottom: 0;
	}

	.preview-image {
		width: 500rpx;
		height: 300rpx;
		border-radius: 16rpx;
		overflow: hidden;
		border: 1rpx solid #eee;
	}

	/* 新增进度条样式（不影响原有样式） */
	.progress-container {
		width: 500rpx; /* 与图片宽度一致，视觉统一 */
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.progress-text {
		font-size: 24rpx;
		color: #666;
		text-align: center;
	}

	.progress-bg {
		width: 100%;
		height: 12rpx;
		background-color: #f5f5f5;
		border-radius: 6rpx;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		background-color: #3CD6FF; /* 与按钮颜色一致，风格统一 */
		transition: width 0.3s ease; /* 进度变化平滑过渡 */
	}
</style>